package fda.datagenerator;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashSet;
import java.util.Random;
import java.util.Set;

public class Generator {

	private final Random r = new Random();

	public static void main(String[] args) throws IOException {
		if((new File("files/datafile.txt")).exists())
			throw new IllegalStateException("\n\n\n!!! Note, the file is already generated in /files/datafile.txt! If you want regenarate it - delete this line");
		Generator gen = new Generator();
		gen.generateDataFile("files/datafile.txt");
	}

	private void generateDataFile(String path) throws IOException {
		int i_temp = 0;
		Set<Integer> keys = new HashSet<Integer>();

		while (keys.size() < 40040) {
			i_temp = r.nextInt(9999999);
			keys.add(new Integer(i_temp));
		}

		String row = "";
		FileWriter fw = null;
		try {
			File f = new File(path);
			if (!f.exists())
				f.createNewFile();

			fw = new FileWriter(f);

			for (int id : keys) {
				row = String.format("%-7d %-15s%-15s%-9d%-54s", id, getRandNoSpaceText(3, 12), getRandNoSpaceText(3, 12), r.nextInt(99999999), getRandText(54));
				fw.append(row + "\n");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fw != null)
				fw.close();
		}

		System.out.println();

	}

	private String getRandText(int length) {
		int lastIndex = text.length();
		String res = "";
		Random r = new Random();
		int startIndex = r.nextInt(lastIndex);
		int tempLength = startIndex + length;

		if (tempLength >= lastIndex) {
			res = text.substring(startIndex, lastIndex);
			res += text.substring(0, length - res.length());
		} else {
			res = text.substring(startIndex, startIndex + length);
		}

		return res.trim();
	}

	private String getRandNoSpaceText(int min, int length) {
		int lastIndex = textNoSpace.length();
		String res = "";
		Random r = new Random();
		int startIndex = r.nextInt(lastIndex);
		int tempLength = startIndex + length;

		if (tempLength >= lastIndex) {
			res = textNoSpace.substring(startIndex, lastIndex);
			res += textNoSpace.substring(0, length - res.length());
		} else {
			res = textNoSpace.substring(startIndex, startIndex + length);
		}

		int randMin = 0;
		while (randMin < min) {
			randMin = r.nextInt(length);
		}

		return res.substring(0, 1).toUpperCase() + res.substring(1, randMin);
	}

	private final String textNoSpace = "Wewanttosortthisrelationontheustomerusingthetwophasemultiwaymergesorttechnique";
	private final String text = "Imortant Note: In each case, also generate a table called Range with 1001 entires, "
			+ "numbered 1 to 1001, in which the i-th entry indicates the minimum and maximum key values of the tuples "
			+ "sorted in block i of the sorted file. The performance of your program will beevaluated using data sets "
			+ "generated by the lab instructors";

}
